<?php
/**
 * 余额记录模型
 * @author 王勇程 <laughskydragon@qq.com>
 */

namespace app\common\model;

class BalanceRecord extends ModelBase
{

    
    // 自动时间戳
    protected $autoWriteTimestamp = true;
    
    // 时间字段
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    
    // 字段类型转换
    protected $type = [
        'id' => 'integer',
        'user_id' => 'integer',
        'amount' => 'float',
        'balance_before' => 'float',
        'balance_after' => 'float',
        'related_id' => 'integer',
        'status' => 'integer',
        'create_time' => 'integer',
        'update_time' => 'integer',
    ];

    /**
     * create_time获取器 - 时间戳转换为日期格式
     */
    public function getCreateTimeAttr($value)
    {
        return $value ? date('Y-m-d H:i:s', $value) : '';
    }

    /**
     * update_time获取器 - 时间戳转换为日期格式
     */
    public function getUpdateTimeAttr($value)
    {
        return $value ? date('Y-m-d H:i:s', $value) : '';
    }

    /**
     * 关联用户表
     */
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    /**
     * 获取用户余额记录
     */
    public function getUserBalanceRecords($userId, $page = 1, $limit = 20)
    {
        return $this->getList([
            'user_id' => $userId
        ], true, 'create_time desc', [
            'list_rows' => $limit,
            'page' => $page
        ]);
    }

    /**
     * 添加余额记录
     */
    public function addRecord($data)
    {
        return $this->save($data);
    }

    /**
     * 获取用户余额统计
     */
    public function getUserBalanceStats($userId, $type = '')
    {
        $where = ['user_id' => $userId];
        if (!empty($type)) {
            $where['type'] = $type;
        }
        
        return [
            'total_income' => $this->stat(array_merge($where, ['amount' => ['>', 0]]), 'sum', 'amount'),
            'total_expense' => $this->stat(array_merge($where, ['amount' => ['<', 0]]), 'sum', 'amount'),
            'count' => $this->stat($where)
        ];
    }
}